package xyz.lwm.lazycat.utility.resource;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import static xyz.lwm.lazycat.utility.PathUtil.normalizePath;

/**
 * @author lwm
 */
public class JarResource implements Resource {

    // jar entry name
    private final String name;

    private final JarFile jarFile;

    private final JarEntry jarEntry;

    JarResource(String name, JarFile jarFile) {
        this.name = name;
        this.jarFile = jarFile;
        this.jarEntry = jarFile.getJarEntry(name);
    }

    @NotNull
    @Override
    public String getName() {
        return new File(name).getName();
    }

    @NotNull
    @Override
    public String getPath() {
        return jarEntry.getName();
    }

    @NotNull
    @Override
    public Resource get(String name) {
        String left = normalizePath(this.name);
        String right = normalizePath(name);
        return new JarResource(left + "/" + right, jarFile);
    }

    @Override
    public boolean exists() {
        return jarEntry != null;
    }

    @Override
    public boolean isFile() {
        return !jarEntry.isDirectory();
    }

    @Override
    public boolean isDir() {
        return jarEntry.isDirectory();
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return isDir() ? null : jarFile.getInputStream(jarEntry);
    }

    @Nullable
    @Override
    public String getClasspath() {
        return getPath();
    }

}